# CBC加密模式
import base64
from Crypto.Cipher import AES
from urllib import parse

AES_SECRET_KEY = 'helloBrook2abcde'  # 此处16|24|32个字符
IV = 'helloBrook2abcde'

# padding算法

BS = len(AES_SECRET_KEY)

# 填充方案
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)

# 解密时删除填充的值

unpad = lambda s: s[0:-ord(s[-1:])]


def cryptoEn(string, key, iv):
    # param string: 原始数据
    # param key: 密钥
    # param iv: 向

    mode = AES.MODE_CBC

    cipher = AES.new(key.encode("utf8"), mode, iv.encode("utf8"))

    encrypted = cipher.encrypt(bytes(pad(string), encoding="utf8"))

    return base64.b64encode(encrypted).decode("utf-8")


# CBC模式的解密代码

def cryptoDe(destring, key, iv):
    # param destring: 需要解密的数据
    # param key: 密钥
    # param iv: 向量

    mode = AES.MODE_CBC

    decode = base64.b64decode(destring)

    cipher = AES.new(key.encode("utf8"), mode, iv.encode("utf8"))

    decrypted = cipher.decrypt(decode)

    return unpad(decrypted).decode("utf-8")


secret_str = cryptoEn('hello', AES_SECRET_KEY, IV)
print(secret_str)

clear_str = cryptoDe(secret_str.encode("utf8"), AES_SECRET_KEY, IV)
print(clear_str)
